# 本章研究的是 文件操作

# 打开文件
f = open('C://Users/22143/Desktop/python.txt','r',encoding='UTF-8')
#读取文件
content=f.readlines()
print(type(content))
for item in content:
    item=item.strip()
    print(item)
#关闭文件
f.close()

print("--------一次读取一行---------")
# 打开文件
f = open('C://Users/22143/Desktop/python.txt','r',encoding='UTF-8')
#读取第一行文件
content=f.readline()
print(f" 第一行:{content.strip()}")

content=f.readline()
print(f" 第二行:{content.strip()}")

# 关闭文件
f.close()


print("------for循环读取文件行----------")
for item in  open('C://Users/22143/Desktop/python.txt','r',encoding='UTF-8'):
     print(item.strip())

# 关闭文件
f.close()

print("---------关闭文件对象------------")
f=open('C://Users/22143/Desktop/python.txt','r',encoding='UTF-8')
f.close()
# 最后通过close,关闭文件对象，就是关闭对文件的占用。


print("--------with open语法-------------")
with open("C://Users/22143/Desktop/python.txt",'r',encoding="UTF-8") as f:
    content=f.readlines()
    for item in content:
        print(item.strip())



print("--------write-------")
# 打开文件
with open("C://Users/22143/Desktop/python.txt","w",encoding="UTF-8")as f:
    # 写入文件
    f.write("hello python")
    # 内容刷新
    f.flush()

with open("C://Users/22143/Desktop/python.txt", "r", encoding="UTF-8") as f:
    content=f.readlines()
    for item in content:
        print(item.strip())



print("------------追加文件--------")
# 打开文件
with open("C://Users/22143/Desktop/python.txt","a",encoding="UTF-8")as f:
    f.write("\nhello world")
    f.flush()

with open("C://Users/22143/Desktop/python.txt", "r", encoding="UTF-8") as f:
 content = f.readlines()
 for item in content:
  print(item.strip())

